/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
/*
  // 递归
    ListNode* swapPairs(ListNode* head) {
        //递归出口：当前结点为null或当前结点下一个结点为null
        if (head == nullptr || head->next == nullptr)
            return head;

        // subResult是head->next->next之后的结点两两交换后的头结点
        ListNode* subResult = swapPairs(head->next->next);
        ListNode* headNext = head->next;
        headNext->next = head;
        head->next = subResult;
        return headNext;
    }
*/

    ListNode* swapPairs(ListNode* head) {
        // 虚拟头节点
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next = head;

        ListNode* prev = dummyHead;
        // 只有当prev指向的结点之后有两个结点时才需要交换
        while(prev->next != nullptr && prev->next->next != nullptr) {
            ListNode* cur = prev->next;
            ListNode* next = cur->next;
            ListNode* subHead = next->next;

           prev->next = next;
           next->next = cur;
           cur->next = subHead;
           prev = cur;
        }
        return dummyHead->next;
    }
};